/*
 * Copyright 2008 Google Inc.
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>

#include "userdb.h"

#define HASH_BYTES 3
#define BASENAME "password"
#define BASENAME_LEN sizeof(BASENAME)


size_t
gvn_userdb_password_filename_length(const char *userdb_path,
                                    const char *user)
{
  size_t user_len = strlen(user);
  size_t userdb_path_len = strlen(userdb_path);
  size_t hash_len = user_len > HASH_BYTES ? HASH_BYTES : user_len;

  return (userdb_path_len
          + 1
          + hash_len
          + 1
          + user_len
          + 1
          + BASENAME_LEN
          + 1);
}


void
gvn_userdb_password_filename(char *filename,
                             const char *userdb_path,
                             const char *user)
{
  size_t user_len = strlen(user);
  size_t hash_len = user_len > HASH_BYTES ? HASH_BYTES : user_len;

  filename[0] = '\0';
  strcat(filename, userdb_path);
  strcat(filename, "/");
  strncat(filename, user, hash_len);
  strcat(filename, "/");
  strcat(filename, user);
  strcat(filename, "/");
  strcat(filename, BASENAME);
}


char *
gvn_userdb_password(const char *filename, char *line)
{
  FILE *stream = NULL;
  char *first_colon, *second_colon, *password_out = NULL;

  stream = fopen(filename, "r");
  if (! stream)
    goto cleanup;

  while (fgets(line, GVN_USERDB_MAX_LINE_LEN, stream))
    {
      /* Skip # or blank lines. */
      if (*line == '#' || !*line)
        continue;

      /* The plain password is between the first and second colons. */
      first_colon = strchr(line, ':');
      if (! first_colon || ! *(first_colon+1))
        continue;

      second_colon = strchr(first_colon + 1, ':');
      if (! second_colon)
        continue;

      *second_colon = '\0';
      password_out = first_colon + 1;
      break;
    }

 cleanup:
  if (stream) fclose(stream);

  return password_out;
}
